package com.frogs.ucenter.v1.service.platform.base;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.ApplicablePlatformEnum;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.system.util.UserMessageStatusEnum;
import com.frogs.system.util.UserRegisterTypeEnum;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.SmsHelper;
import com.frogs.ucenter.dao.UserOpenPlatformInfoDao;
import com.frogs.ucenter.entity.UserAccountInfo;
import com.frogs.ucenter.entity.UserMessageSmsVerifyCode;
import com.frogs.ucenter.entity.UserOpenPlatformInfo;
import com.frogs.ucenter.util.DataCacheKey;
import com.frogs.ucenter.v1.service.PlatformOperationService;
import com.frogs.ucenter.v1.service.impl.UserBaseServiceImpl;
import com.frogs.ucenter.v1.util.ApiConstants;

public abstract class PlatformBaseOperationService extends UserBaseServiceImpl implements PlatformOperationService {

	@Resource
	protected UserOpenPlatformInfoDao userOpenPlatformInfoDao;
	@Resource
	protected SmsHelper smsHelper;
	
	@Override
	public Boolean isExistsOpenid(JSONObject object) {
		String openId = object.getString(ApiConstants.OPEN_ID);
		int openPlatformId = object.getIntValue(ApiConstants.OPEN_PLATFORM_ID);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqOpenId", openId);
		
		if(openPlatformId == OpenPlatformEnum.QQ.getId() || openPlatformId == OpenPlatformEnum.CAIBEI.getId()){
			
			params.put("inOpenPlatformIdList", new Integer[]{OpenPlatformEnum.QQ.getId() , OpenPlatformEnum.CAIBEI.getId()});
		}
		else{
			params.put("eqOpenPlatformId", openPlatformId);
		}
		PageList<UserOpenPlatformInfo> list = userOpenPlatformInfoDao.selectByMap(params, true);
		if (list != null && list.size() > 0) {
			UserOpenPlatformInfo userOpenPlatformInfo = list.get(0);
			Integer userId = userOpenPlatformInfo.getUserId();
			object.put(ApiConstants.USER_ID, userId);
			return true;
		}
		return false;
	}
	
	@Override
	public Boolean updateTokenInfo(JSONObject object) {
		String openId = object.getString(ApiConstants.OPEN_ID);
		String openPlatformId = object.getString(ApiConstants.OPEN_PLATFORM_ID);
		String token = object.getString(ApiConstants.ACCESS_TOKEN);
		String refreshToken = object.getString(ApiConstants.REFRESH_TOKEN);
		Date expiresDate = object.getDate(ApiConstants.EXPIRES_DATE);
		Integer userId = object.getInteger(ApiConstants.USER_ID);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqUserId", userId);
		params.put("eqOpenId", openId);
		params.put("eqOpenPlatformId", openPlatformId);
		params.put("token", token);
		params.put("refreshToken", refreshToken);
		params.put("expiresDate", expiresDate);
		userOpenPlatformInfoDao.updateByMap(params);
		return true;
	}
	
	protected UserAccountInfo otherOpenPlatformRegister(JSONObject object) {
		//新注册
		Map<String, Object> param = new HashMap<String, Object>();
		String username = object.getString(ApiConstants.USER_NAME);
		String email = object.getString(ApiConstants.EMAIL);
		String phone = object.getString(ApiConstants.PHONE);
		String openId = object.getString(ApiConstants.OPEN_ID);
		Integer openPlatformId = object.getInteger(ApiConstants.OPEN_PLATFORM_ID);
		String accountName = "";
		String password = object.getString(ApiConstants.PASSWORD);;
		Integer isRegister = object.getInteger(ApiConstants.IS_REGISTER);
		String nickName = "";
		String expandCode = object.getString(ApiConstants.EXPAND_CODE);
		int count = 0;
		if (StringUtil.isEmail(email)) {//根据邮箱注册
			param.clear();
			param.put("eqEmail", email);
			param.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("该邮箱已经被验证过");
			}
			accountName = creatAccountNameByEmail(email);
		} else if (StringUtil.isMobilePhone(phone)) {//根据手机号码注册
			String code = object.getString("code");
			Response result = smsHelper.checkVerify(phone, code, UserMessageSmsVerifyCode.SendOperationEnum.OPEN_PLATFORM_REGISTER.getValue(), ApplicablePlatformEnum.WEB.getId(), UserMessageStatusEnum.VERIFY.getId());
			if (result.getCode() == ApiResultEnum.FAIL.getId()) {
				throw new ServiceOperationException(result.getTip());
			}
			param.clear();
			param.put("eqPhone", phone);
			param.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("该手机号码已经被验证过");
			}
			String substr = phone.substring(phone.length() - 4, phone.length());
			accountName = creatAccountNameByPhone(substr);
		} else {
			if(UserRegisterTypeEnum.REGISTER_BIND_OPENPLATFOMR.getId() == isRegister){//根据开放平台昵称注册
				if (!StringUtil.isEmpty(username)) {
					accountName = getLegalUserName(username);//获取合法用户名
					nickName = username;
				}
			}else{//用户传入用户名密码进行注册
				if (!StringUtil.isEmpty(username)) {
					if (username.length() < 2 || username.length() > 20) {
						throw new ServiceOperationException("用户名的长度在2-20位");
					}
					if (!Pattern.matches("^[a-zA-Z0-9_\u4e00-\u9fa5]+$", username)) {
						throw new ServiceOperationException("用户名只能是中文，字母，数字，下划线组成");
					}
					param.clear();
					param.put("eqAccountName", username);
					count = userAccountInfoDao.selectCountByMap(param);
					if (count > 0) {
						throw new ServiceOperationException("该用户名已经被使用");
					}
					accountName = username;
				} else {
					throw new ServiceOperationException("用户名不能为空");
				}
			}
		}
		UserAccountInfo userAccountInfo = insertUser(accountName, email, phone, ApplicablePlatformEnum.WEB.getId(), expandCode, password);
		this.initializeOther(userAccountInfo, nickName);
		
		//短信?邮件？
		if (StringUtil.isEmail(email)) {
			cache.remove(DataCacheKey.openPlatformActivateEmailMapkey + StringUtil.md5(openId + openPlatformId + email));
		} else if (StringUtil.isMobilePhone(phone)) {
			cache.remove(DataCacheKey.openPlatformVerifyMapkey + openPlatformId + phone);
		}
		return userAccountInfo;
	}
	
	protected UserAccountInfo openPlatformBind(JSONObject object) throws Exception {
		Integer isphpw = object.getInteger(ApiConstants.IS_PHONE_PASSWORD);
		String password = object.getString(ApiConstants.PASSWORD);
		Map<String, Object> param = new HashMap<String, Object>();
		String userName = object.getString(ApiConstants.USER_NAME);
		String openId = object.getString(ApiConstants.OPEN_ID);
		Integer openPlatformId = object.getInteger(ApiConstants.OPEN_PLATFORM_ID);
		this.verifyParams(userName, param);
		PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(param, false);
		if (list.size() < 1) {
			throw new ServiceOperationException("该用户不存在");
		}
		UserAccountInfo userAccountInfo = list.get(0);
		if (isphpw == 1) {
			String phone = "";
			if (StringUtil.isMobilePhone(userName)) {
				phone = userName;
			} else {
				phone = userAccountInfo.getPhone();
			}
			Response result = smsHelper.checkVerify(phone, password, UserMessageSmsVerifyCode.SendOperationEnum.LOGIN.getValue(), ApplicablePlatformEnum.WEB.getId(), UserMessageStatusEnum.VERIFY.getId());
			if (result.getCode() != ApiResultEnum.SUCCESS.getId()) {
				throw new ServiceOperationException("动态密码错误");
			}
		} else {
			param.put("eqPasswd", StringUtil.md5(password));
			if (userOpenPlatformInfoDao.selectCountByMap(param) < 1) {
				throw new ServiceOperationException("密码错误");
			}
		}
		Integer userId = userAccountInfo.getId();
		param.clear();
		param.put("eqUserId", userId);
		param.put("eqOpenId", openId);
		param.put("eqOpenPlatformId", openPlatformId);
		int count  = userOpenPlatformInfoDao.selectCountByMap(param);
		if (count > 0) {
			throw new ServiceOperationException("该用户已绑定过");
		}
		return userAccountInfo;
	}
	
}
